<template>
    <div class="min-h-screen bg-gradient-to-br from-gray-50 to-blue-50 flex">
        <Nav class="print-hide"></Nav>

        <div class="flex-1 h-screen flex flex-col">
            <!-- 顶部操作栏 -->
            <div
                class="print-hide p-4 md:p-6 bg-white shadow-sm flex flex-wrap md:flex-nowrap justify-between items-center gap-4">
                <div class="flex items-center gap-3">
                    <h1 class="text-lg md:text-xl font-semibold text-gray-800">{{ paperInfo.title }}</h1>
                    <el-tag size="small" type="success" class="!rounded-full">
                        {{ paperInfo.subject }}
                    </el-tag>
                </div>

                <div class="flex items-center gap-4 flex-wrap md:flex-nowrap">
                    <!-- 视图切换 -->
                    <el-radio-group v-model="viewMode" size="small">
                        <el-radio-button label="question">
                            <el-icon class="mr-1">
                                <Grid />
                            </el-icon>试题模式
                        </el-radio-button>
                        <el-radio-button label="paper">
                            <el-icon class="mr-1">
                                <Document />
                            </el-icon>试卷模式
                        </el-radio-button>
                    </el-radio-group>

                    <!-- 操作按钮组 -->
                    <div class="flex gap-2">
                        <el-button type="info" size="small" @click="toggleAllAnalysis">
                            <el-icon class="mr-1">
                                <View />
                            </el-icon>{{ showAllAnalysis ? '收起解析' : '显示解析' }}
                        </el-button>
                        <el-button type="primary" size="small" @click="exportPDF" :loading="exporting">
                            <el-icon class="mr-1">
                                <Document />
                            </el-icon>导出PDF
                        </el-button>
                        <el-button type="success" size="small" @click="handlePrint">
                            <el-icon class="mr-1">
                                <Printer />
                            </el-icon>打印
                        </el-button>
                    </div>
                </div>
            </div>

            <!-- 试卷内容 -->
            <div class="flex-1 overflow-y-auto p-4 md:p-8" ref="paperContent">
                <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-sm p-8 print:shadow-none print:p-0">
                    <!-- 试卷头部信息 -->
                    <div class="text-center mb-8">
                        <h1 class="text-2xl font-bold mb-4">{{ paperInfo.title }}</h1>
                        <div class="text-gray-500 space-y-2">
                            <div class="flex items-center justify-center gap-8">
                                <span>时间：{{ paperInfo.duration }} 分钟</span>
                                <span>题量：{{ questions.length }} 题</span>
                            </div>
                            <div class="flex items-center justify-center gap-4 text-sm">
                                <span>年级：{{ paperInfo.grade }}</span>
                                <span>学期：{{ paperInfo.term }}</span>
                                <span>版本：{{ paperInfo.version }}</span>
                            </div>
                            <div class="border-b border-gray-200 my-4"></div>
                        </div>
                    </div>

                    <!-- 试题分类统计 -->
                    <div v-if="viewMode === 'paper'" class="mb-6 p-4 bg-gray-50 rounded-lg print:hidden">
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                            <div v-for="(count, type) in questionTypeCount" :key="type" class="text-center">
                                <div class="text-sm text-gray-500">{{ getQuestionTypeName(type) }}</div>
                                <div class="text-lg font-medium text-gray-800">{{ count }}题</div>
                            </div>
                        </div>
                    </div>

                    <!-- 试题列表部分优化 -->
                    <div :class="{ 'space-y-8': viewMode === 'question', 'space-y-6': viewMode === 'paper' }">
                        <!-- 空状态提示 -->
                        <div v-if="!questions.length" class="flex flex-col items-center justify-center py-12">
                            <el-empty description="暂无试题数据">
                                <template #image>
                                    <img src="@/assets/images/empty-book.svg" class="w-48" alt="暂无数据" />
                                </template>
                            </el-empty>
                        </div>

                        <!-- 试卷模式 -->
                        <!-- 试卷模式下的题目展示 -->
                        <template v-if="viewMode === 'paper'">
                            <div v-for="(group, type) in groupedQuestions" :key="type" class="print-friendly">
                                <h3 class="text-lg font-medium text-gray-800 mb-4">
                                    {{ getQuestionTypeName(type) }}（共{{ group.length }}题）
                                </h3>
                                <div class="space-y-6">
                                    <div v-for="(question, index) in group" :key="question.id"
                                        class="pb-4 border-b border-gray-100 last:border-none">
                                        <div class="flex items-start gap-3">
                                            <span class="text-gray-500">{{ getQuestionIndex(type, index) }}.</span>
                                            <div class="flex-1">
                                                <div class="text-gray-800 mb-4 questions-content"
                                                    v-html="processContent(question)"></div>
                                                <QuestionOptions :question="question" :mode="viewMode" />
                                                <!-- 试卷模式下的解析部分 -->
                                                <div class="mt-4">
                                                    <el-button type="primary" link class="!p-0"
                                                        @click="question.showAnalysis = !question.showAnalysis">
                                                        {{ question.showAnalysis ? '收起解析' : '查看解析' }}
                                                    </el-button>
                                                    <!-- 修改这里：移除条件类绑定，改用v-show -->
                                                    <div v-show="question.showAnalysis"
                                                        class="analysis-section mt-2 p-4 rounded-lg bg-gray-50">
                                                        <p class="font-medium mb-2">答案：{{ question.answer || '暂无答案' }}
                                                        </p>
                                                        <div>
                                                            <p class="font-medium mb-2">解析：</p>
                                                            <div class="text-gray-600 analysis-content"
                                                                v-html="question.analysis?.body || '暂无解析'"></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>

                        <!-- 试题模式下的题目展示 -->
                        <template v-else>
                            <div v-for="(question, index) in questions" :key="question.id"
                                class="bg-white rounded-lg p-6 shadow-sm hover:shadow-md transition-all">
                                <div class="flex items-start gap-4">
                                    <div class="flex items-center gap-3">
                                        <span class="text-gray-500 text-lg">{{ index + 1 }}.</span>
                                        <!-- 题型标签部分 -->
                                        <span
                                            class="option-title px-3 py-1 bg-blue-100 text-blue-800 text-xs rounded-full print-no-bg">
                                            {{ getQuestionTypeName(question.type) }}
                                        </span>
                                    </div>
                                </div>
                                <div class="mt-4">
                                    <div class="text-gray-800 mb-4 questions-content" v-html="processContent(question)">
                                    </div>
                                    <QuestionOptions :question="question" :mode="viewMode" />
                                    <!-- 试题模式下的解析部分 -->
                                    <div class="mt-4">
                                        <el-button type="primary" link class="!p-0"
                                            @click="question.showAnalysis = !question.showAnalysis">
                                            {{ question.showAnalysis ? '收起解析' : '查看解析' }}
                                        </el-button>
                                        <!-- 同样修改这里 -->
                                        <div v-show="question.showAnalysis"
                                            class="analysis-section mt-2 p-4 rounded-lg bg-gray-50">
                                            <p class="font-medium mb-2">答案：{{ question.answer || '暂无答案' }}</p>
                                            <div>
                                                <p class="font-medium mb-2">解析：</p>
                                                <div class="text-gray-600 analysis-content"
                                                    v-html="question.analysis?.body || '暂无解析'"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- 添加一个隐藏页脚链接的元素 -->
    <!-- <div id="hide-url-footer" class="hidden print:block print:fixed print:bottom-0 print:left-0 print:right-0 print:h-4 print:bg-white print:z-[9999]"></div> -->
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Printer } from '@element-plus/icons-vue'
import html2pdf from 'html2pdf.js'
import Nav from '@/components/nav/index.vue'
import QuestionContent from '@/components/analysis/QuestionContent.vue'
import QuestionOptions from '@/components/analysis/QuestionOptions.vue'
import { convertQuestionType, getDefaultAnswer, processOptions, processContent, analysisJson } from '@/utils/questionHelper'
import { getPaper } from '@/api/common'
import { View } from '@element-plus/icons-vue'  // 添加到已有的图标导入中

const route = useRoute()
const viewMode = ref('question') // question | paper
const exporting = ref(false)
const paperContent = ref(null)
const showAllAnalysis = ref(false)

// 试卷信息
const paperInfo = ref({
    title: '2024春季期末测试',
    subject: '数学',
    totalScore: 100,
    duration: 120,
    grade: '三年级',
    term: '下学期',
    version: '人教版'
})

const paper = ref({})
// 加载题目
const questions = ref([])
const handleQuestions = async (paper_id) => {
    try {
        // 从 store 获取试卷 ID 并调用 API
        const res = await getPaper({
            id: paper_id
        })
        paper.value = res.paper

        questions.value = res.questions.map(item => ({
            id: item.questionId,
            type: convertQuestionType(item.baseType),
            content: item.stem,
            options: processOptions(item.options),
            answer: getDefaultAnswer(convertQuestionType(item.baseType)),
            answer: item.answer,
            analysis: analysisJson(item.answerWebJson),
            showAnalysis: false
        })) || []
        // console.log(questions.value)
        // 根据题目数量设置考试时长
        const questionCount = questions.value.length
        paperInfo.value.duration = Math.floor(questionCount / 10) * 30
        paperInfo.subject = res.paper.subject_name
        paperInfo.version = res.paper.version_name
        paperInfo.grade = res.paper.grade_name
        paperInfo.term = res.paper.term_type_name

        paperInfo.value.title = `${res.paper.title} · ${res.paper.version_name} · ${res.paper.grade_name} · ${res.paper.term_type_name}`
        return res
    } catch (error) {
        console.error('加载试题出错：', error)
        ElMessage.error('加载试题失败，请刷新页面重试')
    }
}

// 按题型分组的试题
const groupedQuestions = computed(() => {
    const groups = {}
    questions.value.forEach(question => {
        if (!groups[question.type]) {
            groups[question.type] = []
        }
        groups[question.type].push(question)
    })
    return groups
})

// 切换所有解析的显示状态
const toggleAllAnalysis = () => {
    showAllAnalysis.value = !showAllAnalysis.value
    questions.value.forEach(question => {
        question.showAnalysis = showAllAnalysis.value
    })
}

// 题型统计
const questionTypeCount = computed(() => {
    const count = {}
    questions.value.forEach(question => {
        count[question.type] = (count[question.type] || 0) + 1
    })
    return count
})

// 获取题目序号
const getQuestionIndex = (type, index) => {
    let startIndex = 1
    for (const t in groupedQuestions.value) {
        if (t === type) {
            return startIndex + index
        }
        startIndex += groupedQuestions.value[t].length
    }
    return index + 1
}

// 修改handlePrint函数
const handlePrint = async () => {
    await nextTick();
    
    const navElement = document.querySelector('nav');
    if (navElement) {
        navElement.style.display = 'none';
    }

    // 获取所有 class 为 analysis-section 的元素
    const analysisSections = document.querySelectorAll('.analysis-section');
    if (showAllAnalysis.value) {
        console.log('showAllAnalysis:',showAllAnalysis.value)
        // 遍历每个元素并强制显示
        analysisSections.forEach(section => {
            section.style.display = 'block';
            section.style.visibility = 'visible';
            section.style.opacity = '1';
            section.style.height = 'auto';
            section.style.overflow = 'visible';
            // 移除可能影响显示的背景色
            section.style.backgroundColor = 'white';
        });
    }


    const printStyle = document.createElement('style');
    printStyle.innerHTML = `
    @media print {
        @page { 
            size: A4; 
            margin: 1.5cm;
        }

        /* 基础打印样式 */
        * {
            -webkit-print-color-adjust: exact !important;
            print-color-adjust: exact !important;
        }

        /* 隐藏不需要的元素 */
        .print-hide,
        .el-button--primary[link] {
            display: none !important;
        }

        /* 图片处理 */
        img {
            max-width: 100% !important;
            height: auto !important;
        }

        /* 隐藏解析按钮 */
        .el-button--primary.is-link {
            display: none !important;
        }
    }`;

    // 打印完成后恢复状态
    const resetPrintState = () => {
        if (navElement) navElement.style.display = '';
        document.head.removeChild(printStyle);
        
        if (showAllAnalysis.value) {
            // 恢复解析部分的原始状态
            analysisSections.forEach(section => {
                // 只恢复display属性，其他保持不变
                if (!showAllAnalysis.value) {
                    const questionId = section.closest('.bg-white.rounded-lg').querySelector('.text-gray-500.text-lg').textContent.replace('.', '').trim();
                    const question = questions.value.find(q => getQuestionIndex(q.type, questions.value.indexOf(q)) == questionId);
                    if (question && !question.showAnalysis) {
                        section.style.display = 'none';
                    }
                }
            });
        }
    };

    window.print();
    setTimeout(resetPrintState, 500);
}

// 获取题型名称
const getQuestionTypeName = (type) => {
    const typeMap = {
        single: '单选题',
        multiple: '多选题',
        truefalse: '判断题',
        fillblank: '填空题',
        essay: '应答题'
    }
    return typeMap[type] || '未知题型'
}

// 导出PDF方法需要更新
const exportPDF = async () => {
    try {
        exporting.value = true;
        const element = paperContent.value;
        const clonedElement = element.cloneNode(true);

        // 移除所有导航和不需要的元素
        const navElements = clonedElement.querySelectorAll('nav, .print-hide');
        navElements.forEach(el => {
            if (el.parentNode) {
                el.parentNode.removeChild(el);
            }
        });

        // 保留已经显示的解析内容（不再移除analysis-section）

        // 移除所有背景色和边框
        const allElements = clonedElement.querySelectorAll('*');
        allElements.forEach(el => {
            el.style.backgroundColor = 'transparent';
            el.style.boxShadow = 'none';

            // 移除题型标签的背景
            if (el.classList.contains('bg-blue-100') ||
                el.classList.contains('rounded-full') ||
                el.classList.contains('el-tag')) {
                el.style.backgroundColor = 'transparent';
                el.style.border = '1px solid #000';
                el.style.color = '#000';
            }
        });

            // 获取所有 class 为 analysis-section 的元素
        const analysisSections = document.querySelectorAll('.analysis-section');
        if (showAllAnalysis.value) {
            console.log('showAllAnalysis:',showAllAnalysis.value)
            // 遍历每个元素并强制显示
            analysisSections.forEach(section => {
                section.style.display = 'block';
                section.style.visibility = 'visible';
                section.style.opacity = '1';
                section.style.height = 'auto';
                section.style.overflow = 'visible';
                // 移除可能影响显示的背景色
                section.style.backgroundColor = 'white';
            });
        }

        // 添加临时打印样式
        const printStyle = document.createElement('style');
        printStyle.innerHTML = `
            @page { size: A4; margin: 1.5cm; }
            body { font-family: Arial, sans-serif; }
            * { 
                background: transparent !important; 
                box-shadow: none !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            .bg-blue-100, .bg-green-100, .rounded-full, .el-tag { 
                background: transparent !important; 
                border: none!important;
                color: #000 !important;
            }
            .option-circle, .option-square {
                border: none!important;
                background: white !important;
            }

        /* 隐藏不需要的元素 */
        .print-hide,
        .el-button--primary[link] {
            display: none !important;
        }

        /* 图片处理 */
        img {
            max-width: 100% !important;
            padding-top: 15px!important;
            height: auto !important;
        }

        /* 隐藏解析按钮 */
        .el-button--primary.is-link {
            display: none !important;
        }
        `;
        document.head.appendChild(printStyle);

        // 使用html2pdf库导出PDF
        const opt = {
            margin: [10, 10, 10, 10], // 上右下左边距，单位mm
            filename: `${paperInfo.value.title}.pdf`,
            image: { type: 'jpeg', quality: 0.98 },
            html2canvas: {
                scale: 2,
                useCORS: true,
                backgroundColor: '#ffffff',
                removeContainer: false,
                ignoreElements: (element) => {
                    // 忽略带有特定背景色的元素
                    const style = window.getComputedStyle(element);
                    return style.backgroundColor !== 'rgba(0, 0, 0, 0)' &&
                        style.backgroundColor !== 'transparent' &&
                        style.backgroundColor !== 'rgb(255, 255, 255)';
                }
            },
            jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
            }
        };

        // 使用克隆的元素导出PDF
        await html2pdf().from(clonedElement).set(opt).save();

        // 移除临时样式
        document.head.removeChild(printStyle);

        if (showAllAnalysis.value) {
            // 恢复解析部分的原始状态
            analysisSections.forEach(section => {
                // 只恢复display属性，其他保持不变
                if (!showAllAnalysis.value) {
                    const questionId = section.closest('.bg-white.rounded-lg').querySelector('.text-gray-500.text-lg').textContent.replace('.', '').trim();
                    const question = questions.value.find(q => getQuestionIndex(q.type, questions.value.indexOf(q)) == questionId);
                    if (question && !question.showAnalysis) {
                        section.style.display = 'none';
                    }
                }
            });
        }

        ElMessage.success('PDF导出成功');
    } catch (error) {
        ElMessage.error('PDF导出失败');
        console.error('PDF导出错误:', error);
    } finally {
        exporting.value = false;
    }
}

onMounted(async () => {
    const paperId = route.query.paper_id
    if (paperId) {
        handleQuestions(paperId)
    }
})
</script>
<style>
.questions-content img {
    display: inline;
}

@media print {

    /* 移除所有背景色 */
    * {
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
        background: none !important;
        box-shadow: none !important;
    }

    /* 只隐藏需要隐藏的元素 */
    /* nav,
    .print-hide,
    .el-button--primary[link],
    .bg-gray-50.rounded-lg,
    .el-radio-group,
    .el-button,
    .bg-gradient-to-br>div>div:first-child,
    .shadow-sm.flex {
        display: none !important;
    } */

    /* 强制隐藏Nav组件 */
    body nav,
    .min-h-screen>nav,
    .min-h-screen>nav.print-hide {
        display: none !important;
        visibility: hidden !important;
    }

    /* 移除题型标签背景 */
    .print-no-bg {
        background: none !important;
        color: #000 !important;
    }

    /* 移除单选题、多选题等标签的背景 */
    .bg-blue-100,
    .bg-green-100,
    .bg-yellow-100,
    .bg-purple-100,
    .bg-red-100 {
        background: none !important;
        color: #000 !important;
    }

    /* 确保导出PDF时没有背景色 */
    .rounded-lg,
    .shadow-sm,
    .bg-white,
    .bg-gray-50,
    .bg-gradient-to-br {
        background: none !important;
        box-shadow: none !important;
    }

    /* 优化打印布局 */
    .min-h-screen {
        min-height: auto !important;
        padding: 0 !important;
        margin: 0 !important;
        display: block !important;
    }

    /* 修复滚动条问题 */
    .flex-1,
    .h-screen,
    .overflow-y-auto {
        height: auto !important;
        overflow: visible !important;
        display: block !important;
    }

    /* 确保内容居中并添加适当的内边距 */
    .max-w-4xl {
        max-width: 100% !important;
        margin: 0 auto !important;
        padding: 0 !important;
    }

    /* 为试卷内容添加适当的间距 */
    .text-center.mb-8 {
        margin-bottom: 20px !important;
    }

    /* 为题目之间添加间距 */
    .pb-4 {
        page-break-inside: avoid;
        margin-bottom: 0.5cm !important;
    }

    /* 为题目内容和选项之间添加间距 */
    .text-gray-800.mb-4 {
        margin-bottom: 12px !important;
    }

    /* 为选项添加间距 */
    .option-item {
        display: inline-flex !important;
        margin-right: 1.5rem !important;
        margin-bottom: 0.5rem !important;
    }

    /* 确保选项圆圈和文本之间有间距 */
    .option-circle,
    .option-square {
        margin-right: 6px !important;
    }

    /* 为题型标题添加间距 */
    .text-lg.font-medium.text-gray-800.mb-4 {
        margin-top: 20px !important;
        margin-bottom: 12px !important;
    }

    /* 为题目序号和内容之间添加间距 */
    .flex.items-start.gap-3 {
        gap: 10px !important;
        display: flex !important;
    }

    /* 确保题目之间有足够的间距 */
    .space-y-6>* {
        margin-bottom: 16px !important;
    }

    /* 移除页面边距 */
    .p-4,
    .p-6,
    .p-8,
    .md\:p-6,
    .md\:p-8 {
        padding: 0 !important;
    }

    /* 添加隐藏页脚URL的强力方法 */
    @page {
        size: A4;
        margin: 1cm 1.5cm 0cm 1.5cm; /* 上右下左，减小底部边距 */
    }

        /* 确保内容不被遮挡 */
    .max-w-4xl {
        max-width: 100% !important;
        margin: 0 !important;
        padding: 0 !important; /* 添加底部内边距 */
    }

    /* 隐藏页脚URL */
    /* #hide-url-footer {
        position: fixed !important;
        bottom: 0 !important;
        left: 0 !important;
        right: 0 !important;
        height: 1px !important;
        background: white !important;
        z-index: 9999 !important;
        display: block !important;
    } */

    /* 移除所有可能显示URL的伪元素 */
    html::after,
    body::after,
    #app::after,
    div::after,
    section::after {
        content: none !important;
        display: none !important;
    }

    /* 隐藏所有链接的URL */
    a[href]::after {
        content: none !important;
    }

    /* 隐藏页面底部的URL显示 */
    html {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }


    /* 修复flex布局在打印时的问题 */
    .flex {
        display: block !important;
    }

    nav,
    .nav,
    :deep(nav) {
        display: none !important;
        visibility: hidden !important;
    }

    /* 强制隐藏所有URL */
    a[href]::after {
        content: none !important;
    }

    /* 隐藏导航栏和顶部操作栏 */
    nav,
    .print-hide {
        display: none !important;
    }

    /* 隐藏解析按钮 */
    .el-button--primary.is-link {
        display: none !important;
    }
}
</style>